package nccloud.web.hrpbm.budgetmake.budgetmake.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import nc.bs.hrpbm.budgetmake.util.PutIndicatoramountToMakeDetail;
import nc.itf.hrpbm.budgetadjust.budgetadjust.IBudgetAdjustVOService;
import nc.itf.hrpbm.budgetmake.budgetmake.IBudgetMakeVOService;
import nc.pub.billcode.itf.IBillcodeManage;
import nc.pub.billcode.vo.BillCodeContext;
import nc.vo.hrpbm.budgetadjust.*;
import nc.vo.hrpbm.budgetindicator.AggBudgetIndicatorVO;
import nc.vo.hrpbm.budgetmake.*;
import nc.vo.pub.ISuperVO;
import nc.vo.pub.VOStatus;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDouble;
import nc.vo.pubapp.AppContext;
import nccloud.commons.lang.StringUtils;
import nccloud.framework.core.exception.BusinessException;
import nccloud.framework.service.ServiceLocator;
import nccloud.framework.web.container.IRequest;
import nccloud.framework.web.container.SessionContext;
import nccloud.itf.hrpbm.pub.common.IHrpbmCommonService;
import nccloud.web.codeplatform.framework.action.base.BaseAction;
import nccloud.web.codeplatform.framework.action.base.RequestDTO;
import nccloud.web.codeplatform.framework.action.base.RequstParamWapper;
import nccloud.web.codeplatform.framework.action.base.VOTransform;

public class LoadBudgetMakeDetailVOAction extends BaseAction {

    @Override
    public Object doAction(IRequest request, RequstParamWapper paramWapper) throws Throwable {
        //json数据转换
        RequestDTO param = VOTransform.toVO(paramWapper.requestString, RequestDTO.class);
        //获取参数
        Map<String, Object> userJson = param.getUserJson();
        String pk = param.getPk();
        if (StringUtils.isEmpty(pk)) {
            throw new BusinessException("请选择支出预算编制单！");
        }
        String formid = param.getFormId();
        String[] tableid = param.getTableId();
        String tailid = param.getTailId();
        String pagecode = param.getPageCode();
        VOTransform tf = new VOTransform(null, pagecode);

        AggBudgetAdjustVO[] vos = tf.toVO(param.getBillCard(), formid, tableid, tailid, AggBudgetAdjustVO.class);

        //通过AppCode获取交易类型code和pk
        IHrpbmCommonService hrp = ServiceLocator.find(IHrpbmCommonService.class);
        String appcode = SessionContext.getInstance().getAppcode();
        Map<String, String> resultMap = hrp.getTransTypeByAppcode(appcode);

        //获得实体VO
        IBudgetAdjustVOService service = ServiceLocator.find(IBudgetAdjustVOService.class);
        AggBudgetAdjustVO vo = service.preAddAggBudgetAdjustVO(vos[0], userJson);
        Map<String, Object> externalData = new HashMap<>();
        vo.getParentVO().setTranstype(resultMap.get("transtypecode"));
        vo.getParentVO().setTranstypepk(resultMap.get("transtypepk"));
        if (vos[0].getParentVO().getBillno() == null) {
            IBillcodeManage service1 = ServiceLocator.find(IBillcodeManage.class);
            String billNo = service1.getBillCode_RequiresNew("hrpbmbudgetadjust", vos[0].getParentVO().getPk_group(), vos[0].getParentVO().getPk_org(), vos[0]);
            vos[0].getParentVO().setBillno(billNo);
        }
        UFDate dbilldate = AppContext.getInstance().getBusiDate();

        vo.getParentVO().setDbilldate(dbilldate);
        getDetailVo(pk,vo);
//        vo.setChildrenVO(detailvos.toArray(new BudgetAdjustDetailVO[0]));
        return buildResult(param, true, externalData, vo);
    }


    public void getDetailVo(String pks,AggBudgetAdjustVO mainvo) throws Throwable {
        if (StringUtils.isEmpty(pks)) {
            throw new BusinessException("请选择支出预算编制单！");
        }
        IBudgetMakeVOService service = ServiceLocator.find(IBudgetMakeVOService.class);
        AggBudgetMakeVO[] vos = service.listAggBudgetMakeVOByPk(pks.split(","));
        if (vos == null) {
            return ;
        }
        List<BudgetMakeDetailVO> detailVOS = new ArrayList<>();
        List<GovpurchVO> govPurchVOS = new ArrayList<>();
        List<AssetAllocationVO> assetAllocationVOS = new ArrayList<>();
        List<SpBudgetMakeDetailVO> spBudgetMakeVOS = new ArrayList<>();
        for (AggBudgetMakeVO vo : vos) {
            // 根据nyear、pk_budgettype、pk_budgetdept查询指标下达的单据数据
            AggBudgetIndicatorVO aggBudgetIndicatorVO = service.queryAggBudgetIndicatorVO(vo.getParentVO().getPk_org(), vo.getParentVO().getNyear(),
                    vo.getParentVO().getPk_budgettype(), vo.getParentVO().getPk_budgetdept());
            PutIndicatoramountToMakeDetail.putIndicatoramountToMakeDetail(vos, aggBudgetIndicatorVO);

            BudgetMakeDetailVO[] detailArr = (BudgetMakeDetailVO[]) vo.getChildren(BudgetMakeDetailVO.class);
            GovpurchVO[] govPurchArr = (GovpurchVO[]) vo.getChildren(GovpurchVO.class);
            AssetAllocationVO[] assetAllocationArr = (AssetAllocationVO[]) vo.getChildren(AssetAllocationVO.class);

            // modify by wy SpBudgetMakeDetailVO
            SpBudgetMakeDetailVO[] SpBudgetMakeDetailArr = (SpBudgetMakeDetailVO[])vo.getChildren(SpBudgetMakeDetailVO.class);

            detailVOS.addAll(Arrays.asList(detailArr));
            if(null != govPurchArr && govPurchArr.length > 0){
                govPurchVOS.addAll(Arrays.asList(govPurchArr));
            }
            if(null != assetAllocationArr && assetAllocationArr.length > 0){
                assetAllocationVOS.addAll(Arrays.asList(assetAllocationArr));
            }
            if(null != SpBudgetMakeDetailArr && SpBudgetMakeDetailArr.length > 0){
                spBudgetMakeVOS.addAll(Arrays.asList(SpBudgetMakeDetailArr));
            }
        }


        Map<String, Object> externalData = new HashMap<>();
        BillCodeContext context = service.getBillCodeContext("hrpbmbudgetmake");
        externalData.put("billCodeContext", context);
        List<BudgetAdjustDetailVO> adjustDetailVos = new ArrayList<>();
        for (BudgetMakeDetailVO cvo : detailVOS) {
            BudgetAdjustDetailVO jvo = new BudgetAdjustDetailVO();
            jvo.setStatus(2);
            jvo.setBudgetno(cvo.getBudgetno());
            jvo.setPk_project(cvo.getPk_project());
            jvo.setPk_inoutclass(cvo.getPk_inoutclass());
            jvo.setPk_fundsource(cvo.getPk_fundsource());
            jvo.setAmount_before_adjust(cvo.getAmount());
            jvo.setAmount_adjust(new UFDouble(0));
            jvo.setAmount_after_adjust(cvo.getAmount());
            jvo.setSrcbillbid(cvo.getPk_budgetmakedetail());
            jvo.setPk_operation(cvo.getPk_operation());
            jvo.setDefdim1(cvo.getDefdim1());
            jvo.setDefdim2(cvo.getDefdim2());
            jvo.setDefdim3(cvo.getDefdim3());
            jvo.setDefdim4(cvo.getDefdim4());
            jvo.setDefdim5(cvo.getDefdim5());
            jvo.setDefdim6(cvo.getDefdim6());
            jvo.setDefdim7(cvo.getDefdim7());
            jvo.setDefdim8(cvo.getDefdim8());
            jvo.setDefdim9(cvo.getDefdim9());
            jvo.setDefdim10(cvo.getDefdim10());
            adjustDetailVos.add(jvo);
        }

        // modify by wy
        List<SpBudgetAdjustDetailVO> spBudgetAdjustDetailVOs = new ArrayList<>();
        if(!spBudgetMakeVOS.isEmpty()){
            for (SpBudgetMakeDetailVO cvo : spBudgetMakeVOS) {
                SpBudgetAdjustDetailVO jvo = new SpBudgetAdjustDetailVO();
                jvo.setStatus(2);
                jvo.setBudgetno(cvo.getBudgetno());
                jvo.setPk_project(cvo.getPk_project());
                jvo.setPk_inoutclass(cvo.getPk_inoutclass());
                jvo.setPk_fundsource(cvo.getPk_fundsource());
                jvo.setAmount_before_adjust(cvo.getAmount());
                jvo.setAmount_adjust(new UFDouble(0));
                jvo.setAmount_after_adjust(cvo.getAmount());
                jvo.setSrcbillbid(cvo.getPk_spbudgetmakedetail());
                jvo.setPk_operation(cvo.getPk_operation());
                spBudgetAdjustDetailVOs.add(jvo);
            }

        }

        List<AdjustGovPurchVO> adjustGovPurchVOList = govPurchVOS.stream()
                .map(sourceVO -> new AdjustGovpurchBuilder().rowno(sourceVO.getRowno()).budgetno(sourceVO.getBudgetno())
                        .pk_project(sourceVO.getPk_project()).pk_depteconomic(sourceVO.getPk_depteconomic())
                        .pk_material(sourceVO.getPk_material()).pk_reportmaterial(sourceVO.getPk_reportmaterial())
                        .govpurch(sourceVO.getGovpurch()).denseleval(sourceVO.getDenseleval())
                        .densetime(sourceVO.getDensetime()).longterm(sourceVO.getLongterm()).secrecyterm(sourceVO.getSecrecyterm())
                        .pk_measdoc(sourceVO.getPk_measdoc()).oldnum(sourceVO.getNum()).oldprice(sourceVO.getPrice())
                        .oldmoney(sourceVO.getMoney()).fiaccountfunds(sourceVO.getFiaccountfunds())
                        .nofiallocationfunds(sourceVO.getNofiallocationfunds()).unitfunds(sourceVO.getUnitfunds())
                        .lastyearfunds(sourceVO.getLastyearfunds()).srcbillbid(sourceVO.getPk_govpurch())
                        .equipmentpurchase(sourceVO.getEquipmentpurchase()).purchasename(sourceVO.getPurchasename())
                        .equipmentname(sourceVO.getEquipmentname()).quasitarget(sourceVO.getQuasitarget())
                        .quantity(sourceVO.getQuantity()).purchaseintype(sourceVO.getPurchaseintype()).issmall(sourceVO.getIssmall())
                        .mediumproportion(sourceVO.getMediumproportion()).microscale(sourceVO.getMicroscale())
                        .enforcementaction(sourceVO.getEnforcementaction()).unsuitabilitycause(sourceVO.getUnsuitabilitycause())
                        .explain(sourceVO.getExplain()).def1(sourceVO.getDef1()).def2(sourceVO.getDef2()).def3(sourceVO.getDef3())
                        .def4(sourceVO.getDef4()).def5(sourceVO.getDef5()).def6(sourceVO.getDef6()).def7(sourceVO.getDef7())
                        .def8(sourceVO.getDef8()).def9(sourceVO.getDef9()).def10(sourceVO.getDef10()).def11(sourceVO.getDef11())
                        .def12(sourceVO.getDef12()).def13(sourceVO.getDef13()).def14(sourceVO.getDef14()).def15(sourceVO.getDef15())
                        .def16(sourceVO.getDef16()).def17(sourceVO.getDef17()).def18(sourceVO.getDef18()).def19(sourceVO.getDef19())
                        .def20(sourceVO.getDef20()).num(sourceVO.getNum()).price(sourceVO.getPrice()).money(sourceVO.getMoney()).status(VOStatus.NEW)
                        .build())
                .collect(Collectors.toList());

        List<AdjustAssetAllocationVO> adjustAssetAllocationVOList = assetAllocationVOS.stream()
                .map(sourceVO -> new AdjustAssetAllocationBuilder().rowno(sourceVO.getRowno()).pk_project(sourceVO.getPk_project())
                        .pk_depteconomic(sourceVO.getPk_depteconomic()).pk_asset(sourceVO.getPk_asset()).pk_asset(sourceVO.getPk_asset())
                        .pk_assetuse(sourceVO.getPk_assetuse()).rent(sourceVO.getRent()).pk_material(sourceVO.getPk_material())
                        .pk_reportmaterial(sourceVO.getPk_reportmaterial()).denseleval(sourceVO.getDenseleval()).densetime(sourceVO.getDensetime())
                        .longterm(sourceVO.getLongterm()).secrecyterm(sourceVO.getSecrecyterm()).stock(sourceVO.getStock()).scrapnum(sourceVO.getScrapnum())
                        .pk_measdoc(sourceVO.getPk_measdoc()).oldassetnum(sourceVO.getAssetnum()).oldprice(sourceVO.getPrice())
                        .oldmoney(sourceVO.getMoney()).carnum(sourceVO.getCarnum()).airdisplacement(sourceVO.getAirdisplacement())
                        .newenergy(sourceVO.getNewenergy()).usage(sourceVO.getUsage()).parameters(sourceVO.getParameters())
                        .purchaseinneed(sourceVO.getPurchaseinneed()).ambientcondition(sourceVO.getAmbientcondition())
                        .professional(sourceVO.getProfessional()).funds(sourceVO.getFunds()).rentallocation(sourceVO.getRentallocation())
                        .rentalneed(sourceVO.getRentalneed()).relet(sourceVO.getRelet()).pricingmethod(sourceVO.getPricingmethod())
                        .averagerent(sourceVO.getAveragerent()).message(sourceVO.getMessage()).srcbillbid(sourceVO.getPk_assetallaction())
                        .def1(sourceVO.getDef1()).def2(sourceVO.getDef2()).def3(sourceVO.getDef3()).def4(sourceVO.getDef4())
                        .def5(sourceVO.getDef5()).def6(sourceVO.getDef6()).def7(sourceVO.getDef7()).def8(sourceVO.getDef8()).def9(sourceVO.getDef9())
                        .def10(sourceVO.getDef10()).def11(sourceVO.getDef11()).def12(sourceVO.getDef12()).def13(sourceVO.getDef13())
                        .def14(sourceVO.getDef14()).def15(sourceVO.getDef15()).def16(sourceVO.getDef16()).def17(sourceVO.getDef17())
                        .def18(sourceVO.getDef18()).def19(sourceVO.getDef19()).def20(sourceVO.getDef20()).status(VOStatus.NEW)
                        .budgetno(sourceVO.getBudgetno()).assetnum(sourceVO.getAssetnum()).price(sourceVO.getPrice()).money(sourceVO.getMoney())
                        .build())
                .collect(Collectors.toList());

        mainvo.setChildrenVO(adjustDetailVos.toArray(new BudgetAdjustDetailVO[0]));
        mainvo.setChildren(AdjustGovPurchVO.class,adjustGovPurchVOList.toArray(new AdjustGovPurchVO[0]));
        mainvo.setChildren(AdjustAssetAllocationVO.class,adjustAssetAllocationVOList.toArray(new AdjustAssetAllocationVO[0]));
        mainvo.setChildren(SpBudgetAdjustDetailVO.class,spBudgetAdjustDetailVOs.toArray(new SpBudgetAdjustDetailVO[0]));
    }
}
